package taskscheduleservicelogic

import (
	"context"
	"github.com/zeromicro/go-zero/core/logx"
	"go-zero-admin/application/job/rpc/internal/model"
	"go-zero-admin/application/job/rpc/internal/svc"
	job "go-zero-admin/application/job/rpc/pb"
	"go-zero-admin/pkg/utils"
)

type SearchCronListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSearchCronListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SearchCronListLogic {
	return &SearchCronListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 查询定时任务列表接口
func (l *SearchCronListLogic) SearchCronList(in *job.SearchScheduleReq) (*job.SearchScheduleRes, error) {
	var res job.SearchScheduleRes

	offset := in.PageRequest.PageSize * (in.PageRequest.PageNo - 1)
	db := l.svcCtx.DB.Model(&model.TaskSchedule{})

	var resList []model.TaskSchedule
	var total int64
	if in.PageRequest.Keyword != "" {
		db = db.Where("task_name like ?", "%"+in.PageRequest.Keyword+"%")
	}
	err := db.Count(&total).Error
	if err != nil {
		return nil, err
	} else {
		err = db.Limit(int(in.PageRequest.PageSize)).Offset(int(offset)).Find(&resList).Error
		if err != nil {
			return nil, err
		}
	}

	res.PageResponse = &job.PageResponse{
		Total:    total,
		PageNo:   in.PageRequest.PageNo,
		PageSize: in.PageRequest.PageSize,
	}

	res.List = make([]*job.TaskScheduleInfo, len(resList))
	for i, item := range resList {
		res.List[i] = &job.TaskScheduleInfo{
			Id:              item.ID,
			TaskName:        item.TaskName,
			TaskType:        item.TaskType,
			TaskStatus:      item.TaskStatus,
			TimeSchedule:    item.TimeSchedule,
			UniqueId:        item.UniqueID,
			MaxRetry:        int64(item.MaxRetry),
			IsOk:            item.IsOk,
			ExecCmd:         item.ExecCmd,
			CreatedAt:       utils.SafeUnix(&item.CreatedAt),
			UpdatedAt:       utils.SafeUnix(&item.UpdatedAt),
			LastExecuteTime: utils.SafeUnix(item.LastExecuteTime),
		}
	}

	return &res, nil
}
